<template>
	<div class="AdPop" style="margin-top: 15px;">
		<div class="dataName"><span class="nameclick">排期记录</span><span>历史记录</span></div>
		<div class="newAdPop">
			<blue-button text="新增" :clickEvent="addClickEvent" class="add-btn">
			</blue-button>
			<blue-button text="结束" :clickEvent="addClickEvent" class="add-btn">
			</blue-button>
			<table class="sv-table" style="overflow-y: auto;max-height: 450px;display: inline-block;">
				<tr class="table-th">
					<th>序号</th>
					<th>广告名称</th>
					<th>广告链接</th>
					<th>广告类型</th>
					<th>所属门店</th>
					<th>更新人</th>
					<th>更新时间</th>
					<th>展示时间</th>
					<th>展示状态</th>
					<th>启用状态</th>
					<th>操作</th>
				</tr>
				<tr class="table-tr" v-for="(item, index) in getDataArray" :key="index">
					<td>{{index}}</td>
					<td>{{item.advTitle}}</td>
					<td>{{item.advLink}}</td>
					<td>{{item.advKind==1?'新人礼':'普通广告'}}</td>
					<td>{{item.storeName}}</td>
					<td>{{item.updateUserName}}</td>
					<td>{{item.createTime | startTime}}</td>
					<td><span>{{item.startTime | startTime}}</span> -- <span>{{item.endTime | startTime}}</span></td>
					<td :class="{redclass:item.displayStatus=='展示中'}">{{item.displayStatus}}</td>
					<td><span :class="[item.advStatus == '1' ? 'banner-qiyong' : 'banner-tingyong']">{{item.advStatus == "1" ? "已启用" : "已停用"}}</span></td>
					<td class="handle-button" ref="handleButton">
						<gray-button text="编辑" :clickEvent="editClickEvent.bind(this, index)"></gray-button>
						<gray-button text="删除" :disabled="item.status == '1'" :clickEvent="deleteClickEvent.bind(this, item.rid,item.status)"></gray-button>
					</td>
				</tr>
			</table>
			<mo-paging v-if="getDataArray.length>0" :page-index="currentPage" :total="Arraycount" :page-size="pageSize" @change="pageChange">
		    </mo-paging>
		</div>
		<div class="oldAdPop">
			
		</div>

		<!-- 编辑或新增的弹框 -->
		<edit-model ref="editModel" title="广告弹框配置" :closeCallback="editModelCloseEvent">
			<div class="slot-banner" slot="main">
				<div>
					<span class="eidt-slot-title">广告名称<span class="required">*</span></span>
					<input type="text" v-model="getDataItem.advTitle" />
				</div>
				<div>
					<span class="eidt-slot-title">展示门店<span class="required">*</span></span>
					<select class="mySelect" v-model="selectedcode">
						<option v-for="(item, index) in stagestoreList" :key="index" :value="item.storeCode+','+item.storeName">{{item.storeName}}</option>
					</select>
				</div>
				<div>
					<span class="eidt-slot-title">广告类型<span class="required">*</span></span>
					<div class="banneranim" v-for="(item, index) in SelectedAdvKind" :key="index">
						<cirle-select class="stylename" :state="item.state == (advKindIndex-1)" :clickEvent="CirleSelectedAdvKind.bind(this, item.state)"></cirle-select>
						<span>{{item.text}}</span>
					</div>
				</div>
				<div>
					<span class="eidt-slot-title">展示状态<span class="required">*</span></span>
					<div class="banneranim" v-for="(item, index) in SelectedAdvStatus" :key="index">
						<cirle-select class="stylename" :state="item.state == advStatusIndex" :clickEvent="CirleSelectedAdvStatus.bind(this, item.state)"></cirle-select>
						<span>{{item.text}}</span>
					</div>
				</div>
				<div class="poptime">
					<span class="eidt-slot-title">展示时间<span class="required">*</span></span>
					<el-date-picker class="pickertime" v-model="startTime" :date="startTime" type="datetime" placeholder="选择日期时间" style="width: 280px;margin-right: 10px;">
					</el-date-picker>
					<el-date-picker class="pickertime" v-model="endTime" :date="startTime" type="datetime" placeholder="选择日期时间" style="width: 280px;">
					</el-date-picker>
				</div>
				<div>
					<span class="eidt-slot-title">广告图片上传<span class="required">*</span></span>
					<div class="upload-box">
						<!-- <img-upload :imgShowList="getBannerUrl ? [getBannerUrl] : []"></img-upload> -->
						<img-upload ref="bannerImg" :deleteCallback="bannerDeleteCallback" :imgShowList="getDataItem.advImg ? [getDataItem.advImg] : []">
						</img-upload>
					</div>
				</div>
				<div>
					<span class="eidt-slot-title">广告链接<span class="required">*</span></span>
					<page-path :changeEvent="changeEvent" :defaultChooseProps="valueArray" rootSelector="#edit-model-box"></page-path>
				</div>
				<div class="fabu-box">
					<blue-button text="发布" :clickEvent="submitClickEvent"></blue-button>
				</div>
			</div>
			<!--<div slot="slide">
				<search-product ref="searchModel" @getgoodscodedata="getgoodscode"></search-product>
			</div>-->
		</edit-model>
		<m-toast ref="toast"></m-toast>
		<m-dialog ref="dialog"></m-dialog>
	</div>

</template>

<script>
	import BlueButton from "../BlueButton";
	import SearchProduct from "../SearchProduct";
	/*import SearchEncode from "../../edit-components/SearchEncode";*/
	import CirleSelect from "../CirleSelect";
	import GrayButton from "../GrayButton";
	import EditModel from "../EditModel";
	import getData from './getData';
	import enableOdisable from "./enableOdisable";
	import publish from "./editOAdd";
	import getStoreCode from "./getStoreCode";
	import deleteFn from "./delete";
	import add from "./add";
	import getCode from "../../edit-containers/EditHome/ProductItem/getGoodsCode.js";
	import { DatePicker } from "element-ui";
	// import 'element-ui/lib/theme-chalk/index.css'
	import imgUpload from "../../real-components/ImgUpload2";
	import Toast from "../Toast";
	import Dialog from "../Dialog";
	import Validator from "../../utils/validator";
	import { getPageNameOrVirtualPageName } from "../../utils/getPageName";
	import PagePath from "../../edit-components/PagePath";
	import pagination from "../../edit-components/pagination";
	/*import { mapMutations } from "vuex";*/

	export default {
		data() {
			return {
				dataArray: [],
				dataItem: null,
				params: {},
				startTime: "",
				endTime:'',
				bannerUrl: "", //用于上传的banner图片
				handleType: "add",
				SelectedAdvStatus: [{
					state: 0,
					text: "禁用"
				},{
					state: 1,
					text: "启用"
				}],
				advStatusIndex:0,//首页广告状态（0禁用，1启用）
				SelectedAdvKind: [{
					state: 0,
					text: "新人礼"
				}, {
					state: 1,
					text: "普通广告"
				}],
				advKindIndex:1,//广告种类（1新人礼2普通广告）
				//链接地址
				selected: "",
				valueArray: [],
				//门店信息
				selectedcode: '',
				stagestoreList: [],
				//分页
				pageSize: 5, //每页显示20条数据
				currentPage: 1, //当前页码
				count: 0, //总记录数
			}
		},
		components: {
			"blue-button": BlueButton,
			"search-product": SearchProduct,
			"cirle-select": CirleSelect,
			"gray-button": GrayButton,
			"edit-model": EditModel,
			"el-date-picker": DatePicker,
			"img-upload": imgUpload,
			"m-toast": Toast,
			"m-dialog": Dialog,
			"page-path": PagePath,
			"mo-paging": pagination,
		},
		computed: {
			//获取表格渲染数据
			getDataArray() {
				return this.dataArray;
			},
			//获得选中的数据item
			getDataItem() {
				if(this.dataItem) {
					return this.dataItem;
				}
				return {};
			},
			//获取分页页面
			Arraycount() {
				return this.count;
			},
			//获取上传的图片
			getBannerUrl() {
				return this.bannerUrl;
			},
		},
		methods: {
			//获取配置路由链接子组件路径的值
			changeEvent(data) {
				this.selected = data
			},
			//路径地址展示
			urlfn(item) {
				if(item.advLink && JSON.parse(item.advLink).url) {
					return JSON.parse(item.advLink).url.UIContent
				} else {
					return "--"
				}
			},
			//获取门店code
			getShopCode() {
				let callback = (data) => {
					this.stagestoreList = data;
				}
				getStoreCode(callback);
			},
			//模态框关闭后的回调事件
			editModelCloseEvent() {
				/*this.getAdPopData()*/
			},
			//初始化数据列表
			getAdPopData() {
				let params = {
					length: this.pageSize,
					pageNum: this.currentPage,
					start: (this.currentPage - 1) * this.pageSize,
					advType:1,//弹窗广告
					queryType:1,//(0历史记录，1排期记录)
				}
				let callback = (data) => {
					this.dataArray = data.results;
					this.count = data.totalCount
				}
				getData(callback, params);
			},
			//分页获取数据
			pageChange(page) {
				this.currentPage = page
				this.getAdPopData()
			},
			//新增按钮的事件
			addClickEvent() {
				if(!getCookie("sessionId")) {
					this.$refs.toast.toast("登录失效，请重新登录");
					return
				}
				this.handleType = "add";
				this.$refs.editModel.showCover();
				this.dataItem = {};
				//活动时间
				this.startTime = "";
				this.endTime = "";
				//门店信息
				selectedcode=""
				//路由跳转路径
				this.valueArray = []
				this.selected = ""
				//配置图片链接
				this.bannerUrl = "";
				if(this.$refs.bannerImg) {
					this.$refs.bannerImg.deleteImg();
				}
				//状态和广告类型
				this.advStatusIndex = 0;
				this.advKindIndex = 1;
			},
			//编辑按钮的事件
			editClickEvent(index) {
				this.handleType = "edit";
				//显示cover
				this.$refs.editModel.showCover();
				//编辑当前的数据
				this.dataItem = this.getDataItemFn(index);
				console.log(this.dataItem,"77777")
				//初始化主图
				this.bannerUrl = this.dataItem.advImg;
				//初始化生效时间
				this.startTime = this.dataItem.startTime;
				this.endTime = this.dataItem.endTime;
				//初始化配置路径
				if(this.dataItem.advLink) {
					//this.valueArray = JSON.parse(this.dataItem.advLink).url.valueArray
					//this.selected = JSON.parse(this.dataItem.advLink).url
				}
				//初始化广告类型和状态
				this.advStatusIndex = this.dataItem.advStatus;
				this.advKindIndex = this.dataItem.advKind;
				//初始化门店信息
				this.selectedcode = this.dataItem.storeCode+','+this.dataItem.storeName
			},
			//发布按钮的点击事件
			async submitClickEvent() {
				let response = await this.$refs.bannerImg.upload();
				if(response.status === 0) {
					this.errorToast("图片上传失败");
					return;
				}
				if(response.status === 2) {
					if(!this.bannerUrl) {
						this.errorToast("未上传图片");
						return;
					}
				}
				if(response.status === 1) {
					this.bannerUrl = response.data[0];
					console.log(this.bannerUrl);
				}
				this.publishFn();
			},
			//删除按钮的事件
			deleteClickEvent(id, status) {
				if(status == 1) {
					return
				}
				let msg = "确定要删除该资源位吗？";
				let confirmFn = () => {
					let params = {
						rid: id,
						storeCode: this.storeCode,
						relGroup: this.relGroup
					}
					let callback = data => {
						this.dataArray = data;
						this.$refs.toast.toast("删除成功");
					}
					let errFn = (data) => {
						this.$refs.toast.toast(data);
					}
					deleteFn(params, this.relGroup, callback, errFn);
				}
				this.infoDialog(msg, confirmFn);
			},
			publishFn() {
				this.getParams();
				//校验参数的完整性
				console.log(this.params,"这是要上传的params");
				//检验广告标题
				if(!this.params.advTitle) {
					this.$refs.toast.toast("广告标题不能为空");
					return;
				}
				//生效开始时间
				if(!this.startTime) {
					this.$refs.toast.toast("生效开始时间不能为空");
					return;
				}
				//生效结束时间
				if(!this.endTime) {
					this.$refs.toast.toast("生效结束时间不能为空");
					return;
				}
				//门店信息
				if(!this.selectedcode) {
					this.$refs.toast.toast("门店信息不能为空");
					return;
				}
				//广告链接
				if(!this.selected) {
					this.$refs.toast.toast("广告链接不能为空");
					return;
				}
				//检验主图
				if(!this.params.advImg) {
					this.$refs.toast.toast("请上传图片");
					return;
				}
				let callback = (data) => {
					this.$refs.toast.toast("发布成功");
					this.dataArray = data;
					this.$refs.editModel.hideCover();
					this.valueArray = [this.selected]
				}
				let errFn = (data) => {
					this.$refs.toast.toast(data);
				}
				if(this.handleType === "edit") {
					publish(this.params, this.relGroup, callback, errFn);
				} else if(this.handleType === "add") {
					add(this.params, this.relGroup, callback, errFn);
				}

			},
			//格式化发布的参数
			getParams() {
				//判断参数
				var obj = {
					"url": this.selected
				}
				var str = JSON.stringify(obj);
				let strcode = this.selectedcode.split(",");
				this.params = {
					advTitle: this.getDataItem.advTitle,
					advLink:str,
					advKind:this.advKindIndex,
					advStatus:this.advStatusIndex,
					advImg: this.getBannerUrl,
					storeCode:strcode[0],
					storeName:strcode[1],
				}
				if(this.handleType === "edit") {
					this.params = Object.assign({}, this.params, {
						rid: this.getDataItem.rid,
					});
				}
				if(this.startTime) {
					let startdate = new Date(this.startTime);
					let startshowTime = `${startdate.getFullYear()}-${startdate.getMonth() + 1 > 9 ? startdate.getMonth() + 1:'0' + (startdate.getMonth() + 1)}-${startdate.getDate()> 9 ? startdate.getDate() : '0' + startdate.getDate()}  ${startdate.getHours() > 9 ? startdate.getHours() : '0' + startdate.getHours()}:${startdate.getMinutes() > 9 ? startdate.getMinutes() : '0' + startdate.getMinutes()}`
				}
				if(this.endTime){
					let endtdate = new Date(this.endTime);
					let endshowTime = `${endtdate.getFullYear()}-${endtdate.getMonth() + 1 > 9 ? endtdate.getMonth() + 1:'0' + (endtdate.getMonth() + 1)}-${endtdate.getDate()> 9 ? endtdate.getDate() : '0' + endtdate.getDate()}  ${endtdate.getHours() > 9 ? endtdate.getHours() : '0' + endtdate.getHours()}:${endtdate.getMinutes() > 9 ? endtdate.getMinutes() : '0' + endtdate.getMinutes()}`
				}
				this.params = Object.assign({}, this.params, {
						startTimeStr:startshowTime,
					    endTimeStr:endshowTime,
					});
			},
			//返回对应index的数据
			getDataItemFn(index) {
				return this.dataArray[index];
			},
			errorToast(msg, duration = 1000) {
				this.$refs.toast.toast(msg, duration);
			},
			infoDialog(msg, confirmFn) {
				this.$refs.dialog.dialog({
					msg,
					confirmFn
				});
			},
			CirleSelectedAdvKind(state) {
				this.advKindIndex = Number(state)+1;
			},
			CirleSelectedAdvStatus(){
				this.advStatusIndex = state;
			},
			//插件那边删除图片，这边也要删除图片
			bannerDeleteCallback() {
				console.log("删除对应的图片");
				this.bannerUrl = "";
			}
		},
		filters: {
			startTime: function(time) {
				if(time) {
					let date = new Date(time);
					return `${date.getFullYear()}-${date.getMonth() + 1 > 9 ? date.getMonth() + 1:'0' + (date.getMonth() + 1)}-${date.getDate()> 9 ? date.getDate() : '0' + date.getDate()}  ${date.getHours() > 9 ? date.getHours() : '0' + date.getHours()}:${date.getMinutes() > 9 ? date.getMinutes() : '0' + date.getMinutes()}`;
				} else {
					return "--"
				}

			}
		},
		created() {

		},
		mounted() {
			if(!getCookie("sessionId")) {
				this.$refs.toast.toast("登录失效，请重新登录");
			}
			this.getAdPopData();
			this.getShopCode()
		},
		watch: {
			
		}

	}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
	.add-btn {
		margin-bottom: 10px;
		display: inline-block;
		float: left;
		margin-right: 10px;
	}
	
	.handle-button>div {
		margin: 0 1px;
	}
	
	.handle-button .sdrag-gray-btn {
		/* height: 26px; */
	}
	
	.banner-edit-box {
		position: fixed;
		left: 0;
		top: 0;
	}
	
	.edit-cover {
		position: absolute;
		left: 0;
		top: 0;
		background: #000;
		width: 100%;
		height: 100%;
		opacity: 0;
		transition: opacity 0.3s;
	}
	
	.edit-cover-show {
		/* opacity: 0.4; */
		/* transition: all 1s;  */
	}
	
	.edit-cover-hide {
		/* opacity: 0; */
		/* transition: all 1s ease-out 1s; */
	}
	
	.edit-content {
		background: #fff;
		width: 600px;
		height: 300px;
		position: absolute;
		left: 0;
		right: 0;
		border-radius: 3px;
		margin: auto;
		/* transform: translateY(30px); */
		transform: translateY(-300px);
		transition: transform 0.3s ease-out;
	}
	
	.edit-content-show {
		/* transform: translateY(30px);  */
	}
	
	.edit-title-box {
		display: flex;
		box-sizing: border-box;
		padding: 15px;
		width: 100%;
		height: 60px;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1px solid #ddd;
	}
	
	.edit-close {
		font-size: 20px;
		font-weight: bold;
		color: #ddd;
		cursor: pointer;
	}
	
	.edit-close:hover {
		color: #444;
	}
	/* 编辑区域的样式 */
	
	.slot-banner>div {
		display: flex;
		/* margin-top:  */
		margin-bottom: 10px;
		align-items: center;
	}
	
	.slot-banner>div input[type=radio] {
		width: unset;
	}
	.el-date-editor {
		width: 50%;
		border: 1px solid #ddd;
		height: 28px;
	}
	
	.el-date-editor input {
		height: 28px;
	}
	
	.el-input__inner {
		height: 28px !important;
	}
	
	.upload-box {
		border: 1px solid #ddd;
	}
	
	.banner-qiyong {
		background-color: #2980b9;
		color: #fff;
		font-size: 12px;
		border-radius: 3px;
		padding: 1px;
	}
	
	.banner-tingyong {
		background-color: #e74c3c;
		color: #fff;
		font-size: 12px;
		border-radius: 3px;
		padding: 1px;
	}
	
	.fabu-box {
		display: flex;
		justify-content: center;
		margin-top: 30px;
	}
	
	.stylename {
		display: inline-block;
		vertical-align: middle;
		margin: 0px 15px;
	}
	
	.AdPop .banneranim {
		display: inline-block;
		margin-right: 15px;
	}
	
	.AdPop .bannermySelect {
		border: 1px solid #ddd;
		padding: 5px 5px;
		width: 50%;
		height: unset;
		margin-bottom: 10px;
	}
	
	.sortspan {
		display: inline-block;
		width: 20px;
	}
	
	.AdPop .mySelect {
		border: 1px solid #ddd;
		padding: 5px 5px;
		width: 50%;
		height: unset;
	}
	.dataName{
		text-align: left;
		margin-bottom: 10px;
		font-size: 16px;
	}
	.dataName span{
		width: 100px;
		height: 30px;
		line-height: 30px;
		text-align: center;
		margin-right: 15px;
	}
	.nameclick{
		color: #3876af;
		border-bottom: 1px solid #3876af;
	}
	.pickertime>input[type=text].el-input__inner{
		width: 100% !important;
	}
	.redclass{
		color: red;
	}
</style>